import { Plugin, ResolvedConfig } from "vite"
import { filePathDefault, metaNameDefault, ViteAppVersionConfig } from "./appVersionConfig"
import fs from "node:fs"
import path from "node:path"

export const appVersionMark = (config?:ViteAppVersionConfig, logDetail?:boolean):Plugin => {
    let viteConfig: ResolvedConfig
    let version: number
    return {
      name: "vite-app-version",
      configResolved(resolvedConfig: ResolvedConfig) {
        viteConfig = resolvedConfig
        version = (new Date()).getTime()
        if(logDetail)
          console.log(`[vav] timestamp ${version}`)
      },
      buildStart() {
        const filePath = path.join(viteConfig.publicDir, config?.filePath || filePathDefault)
        const content = version.toString()
        if (!fs.existsSync(viteConfig.publicDir)) {
          fs.mkdirSync(viteConfig.publicDir)
        }
        fs.writeFileSync(filePath, content)
        if(logDetail)
          console.log(`[vav] wrote timestamp to ${filePath}`)
      },
      transformIndexHtml(html:string) {
        const headIdx = html.indexOf('</head>')
        if(headIdx === -1)
          throw Error('missing <head> in index.html')
        const lineEndBeforeHead = html.lastIndexOf('\n', headIdx)
        let headIntended = 2
        if(lineEndBeforeHead !== -1)
          headIntended = headIdx-lineEndBeforeHead-1
        let insert = '\n'+' '.repeat(headIntended+2)
        const metaName = config?.metaName || metaNameDefault
        insert += `<meta name="${metaName}" content="${version}">`
        const front = html.substring(0, lineEndBeforeHead)
        const back = html.substring(lineEndBeforeHead)
        if(logDetail)
          console.log(`\n[vav] wrote timestamp to <meta name="${metaName}">`)
        return front + insert + back
      }
    }
  }